<template>
  <div class="wiki-label-select-search">
    <el-select
      :id="`form_${field.fieldName}`"
      :placeholder="placeholder"
      :value="value"
      clearable
      filterable
      multiple
      allow-create
      default-first-option
      @change="changeSelect"
      @blur.native.capture="handleBlur"
      popper-class="wiki-type-popper"
    >
      <el-option
        v-for="(item, index) in options"
        :key="`${item.value}_${index}`"
        :label="item.text"
        :value="item.value"
      >
      </el-option>
    </el-select>
  </div>
</template>

<script>
import { defineComponent, computed } from 'vue';
import i18n from '@src/locales';
import platform from '@src/platform';
export default defineComponent({
  name: 'wiki-label-search',
  props: {
    field: {
      type: Object,
      default: null,
    },
    value: {
      type: [Number, String, Array],
      default: [],
    },
  },
  computed: {
    placeholder() {
      return i18n.t('wiki.list.labelSearch.pla1')
    }
  },
  emits: ['update'],
  setup(props, { emit }) {
    // 是否多选 连接器select默认是单选
    const dataSource = computed(() => props.field?.setting?.dataSource || []);
    const options = computed(() =>
      dataSource.value.map(s =>
        typeof s === 'string' ? { text: s, value: s } : s
      )
    );

    // 改变值
    function changeSelect(value) {
      if(value.length > 4) { 
        // 标签数量不能大于4
        platform.notification({
          title: i18n.t('wiki.create.textTitle.tips7'),
          type: 'error',
        })
        return
      }
      const labelLength = value.length && value[value.length -1].length
      if(labelLength > 10) {
        platform.notification({
          title: i18n.t('wiki.create.textTitle.tips5'),
          type: 'error',
        })
        return
      }
      emit('update', value);
    }

    function handleBlur(event) {
      const current = event.target.value
      if(!current) return
      if(props.value.length && props.value.includes(current)) return
      const value = [...props.value, current]
      changeSelect(value)
    }

    return {
      options,
      changeSelect,
      handleBlur,
    };
  },
});
</script>
<style lang="scss">
.wiki-label-select-search {
  .el-select {
    .el-icon-arrow-up {
      display: none;
    }
  }
}
.wiki-type-popper {
  display: none;
}
</style>
